package com.example.homework.bean;



import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

public class SnakeGameView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private Thread gameThread;
    private SurfaceHolder surfaceHolder;
    private boolean isPlaying;
    private int screenX, screenY;
    private int gridSize = 20;
    private int score = 0;
    private Direction currentDirection = Direction.RIGHT;

    private Point food;
    private Paint snakePaint, foodPaint, gridPaint;
    private ScoreListener scoreListener;
    private Random random;
    private boolean isGameOver = false;
    private List<Point> snake = new CopyOnWriteArrayList<>(); // 或使用同步块


    public enum Direction {UP, DOWN, LEFT, RIGHT}

    public interface ScoreListener {
        void onScoreUpdated(int score);

        void onGameOver();
    }

    public SnakeGameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        setFocusable(true);

        surfaceHolder.setFormat(android.graphics.PixelFormat.RGBA_8888);

        snakePaint = new Paint();
        snakePaint.setColor(Color.GREEN);
        snakePaint.setStyle(Paint.Style.FILL);

        foodPaint = new Paint();
        foodPaint.setColor(Color.RED);
        foodPaint.setStyle(Paint.Style.FILL);

        gridPaint = new Paint();
        gridPaint.setColor(Color.LTGRAY);
        gridPaint.setStyle(Paint.Style.STROKE);
        gridPaint.setStrokeWidth(1);

        random = new Random();
    }

    public void setScoreListener(ScoreListener listener) {
        this.scoreListener = listener;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (screenX == 0 || screenY == 0) {
            surfaceChanged(holder, PixelFormat.RGBA_8888, getWidth(), getHeight());
        }
        startGame();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        screenX = width;
        screenY = height;
        initGame();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isPlaying = false;
        if (gameThread != null) {
        try {
            gameThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        gameThread = null;
        }
    }

    private void initGame() {
        snake.clear();
        int cellSize = getCellSize();
        if (cellSize == 0) return;
        // 初始化蛇的位置
        int centerX = screenX / (2 * cellSize);
        int centerY = screenY / (2 * cellSize);
        centerX = Math.max(2, Math.min(centerX, screenX/cellSize - 2));
        centerY = Math.max(2, Math.min(centerY, screenY/cellSize - 2));
        if (centerX < 0 ) centerX = 0;
        if (centerY < 0) centerY = 0;

        snake.add(new Point(centerX, centerY));
        if (centerX >= 1) snake.add(new Point(centerX - 1, centerY)); // 确保至少有一个节点
        if (centerX >= 2) snake.add(new Point(centerX - 2, centerY));

        spawnFood();
        score = 0;
        if (scoreListener != null) {
            post(() -> scoreListener.onScoreUpdated(score));
        }
    }

    private void spawnFood() {
        int maxRetries = 100;
        int cellSize = getCellSize();
        int maxX = screenX / cellSize - 1;
        int maxY = screenY / cellSize - 1;

        boolean validPosition;
        do {
            if (maxRetries-- <= 0) break;
            validPosition = true;
            int x = random.nextInt(maxX);
            int y = random.nextInt(maxY);
            food = new Point(x, y);

            // 确保食物不会出现在蛇身上
            for (Point segment : snake) {
                if (segment.x == food.x && segment.y == food.y) {
                    validPosition = false;
                    break;
                }
            }
        } while (!validPosition);
    }

    private int getCellSize() {
        int size = Math.min(screenX, screenY) / gridSize;
        System.out.println("cellSize: " + size + ", screenX: " + screenX + ", screenY: " + screenY); // 新增日志
        return size;
    }

    @Override
    public void run() {
        System.out.println("游戏线程启动，isPlaying: " + isPlaying);
        while (isPlaying) {
            update();
            draw();
            control();
        }
        System.out.println("游戏线程结束，isPlaying: " + isPlaying);
    }

    private void update() {
        // 移动蛇
        if (snake.isEmpty()) {
            // 重置游戏或初始化蛇（根据业务逻辑）
            initGame();
            return;
        }
        Point head = new Point(snake.get(0));
        System.out.println("移动前头部坐标：(" + head.x + ", " + head.y + ")");

        switch (currentDirection) {
            case UP:
                head.y--;
                break;
            case DOWN:
                head.y++;
                break;
            case LEFT:
                head.x--;
                break;
            case RIGHT:
                head.x++;
                break;
        }
        System.out.println("移动后头部坐标：(" + head.x + ", " + head.y + ")");

        // 检查是否吃到食物
        if (head.x == food.x && head.y == food.y) {
            score += 10;
            if (scoreListener != null) {
                post(new Runnable() {
                    @Override
                    public void run() {
                        scoreListener.onScoreUpdated(score);
                    }
                });
            }
            spawnFood();
        } else {
            // 如果没吃到食物，移除尾部
            snake.remove(snake.size() - 1);
        }

        // 检查是否碰撞边界
        int cellSize = getCellSize();
        if (head.x < 0 || head.x >= screenX / cellSize ||
                head.y < 0 || head.y >= screenY / cellSize) {
            gameOver();
            return;
        }

        // 检查是否碰撞自身
        for (Point segment : snake) {
            if (segment.x == head.x && segment.y == head.y) {
                gameOver();
                return;
            }
        }

        // 添加新头部
        snake.add(0, head);
    }

    private void draw() {
        if (surfaceHolder.getSurface().isValid()) {
            Canvas canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.BLACK);

            int cellSize = getCellSize();

            // 绘制网格（可选）
            for (int x = 0; x < screenX; x += cellSize) {
                canvas.drawLine(x, 0, x, screenY, gridPaint);
            }
            for (int y = 0; y < screenY; y += cellSize) {
                canvas.drawLine(0, y, screenX, y, gridPaint);
            }

            // 绘制食物
            canvas.drawRect(food.x * cellSize, food.y * cellSize,
                    (food.x + 1) * cellSize, (food.y + 1) * cellSize, foodPaint);

            // 绘制蛇
            for (int i = 0; i < snake.size(); i++) {
                Point segment = snake.get(i);
                // 蛇头和身体颜色区分
                if (i == 0) {
                    snakePaint.setColor(Color.rgb(0, 255, 0));
                } else {
                    // 身体颜色渐变
                    int green = 255 - (i * 10 > 200 ? 200 : i * 10);
                    snakePaint.setColor(Color.rgb(0, green, 0));
                }
                canvas.drawRect(segment.x * cellSize, segment.y * cellSize,
                        (segment.x + 1) * cellSize, (segment.y + 1) * cellSize, snakePaint);
            }

            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    private void control() {
        try {
            // 控制游戏速度
            gameThread.sleep(100 - (score / 10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void startGame() {
        if (isGameOver) {
            initGame();
            isGameOver = false;
        }
        if (gameThread == null || !gameThread.isAlive()) {
            isPlaying = true;
            gameThread = new Thread(this); // 假设 SnakeGameView 实现了 Runnable 接口
            gameThread.start();
        }
        isPlaying = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    public void pauseGame() {
        isPlaying = false;
        if (gameThread != null) {
            try {
                gameThread.join();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            gameThread = null;
        }
    }

    public void setDirection(Direction direction) {
        // 防止180度转向
        if ((direction == Direction.UP && currentDirection == Direction.DOWN) ||
                (direction == Direction.DOWN && currentDirection == Direction.UP) ||
                (direction == Direction.LEFT && currentDirection == Direction.RIGHT) ||
                (direction == Direction.RIGHT && currentDirection == Direction.LEFT)) {
            return;
        }
        currentDirection = direction;
        System.out.println("当前方向：" + currentDirection);
    }

    private void gameOver() {
        isGameOver = true;
        isPlaying = false;
        initGame();
        post(() -> {
            if (scoreListener != null) {
                scoreListener.onScoreUpdated(-1); // 分数显示为 -1 表示游戏结束
                scoreListener.onGameOver(); // 通知 Activity 游戏已结束
            }
        });
    }
    public boolean isGameOver() {
        return isGameOver;
    }
    // isPlaying 已存在，直接返回其取反值（暂停时 isPlaying 为 false）
    public boolean isPaused() {
        return !isPlaying;
    }
    public void resumeGame() {
        if (isGameOver) {
            // 游戏结束后不可恢复，需重新开始
            initGame(); // 重置游戏状态
            isGameOver = false; // 清除游戏结束状态
        }
        if (!isPlaying && gameThread == null) { // 确保线程未运行时创建新线程
            isPlaying = true;
            gameThread = new Thread(this);
            gameThread.start();
        }
    }
}

